package extensions.romario.packet;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public abstract class AbstractPacket {

    protected short _id;
    protected ObjectInputStream _in;
    protected ObjectOutputStream _out;
    
    public AbstractPacket(short id)
    {
        _id = id;
    }

    public abstract void readContent() throws IOException;

    public final void send() throws IOException
    {
    	writeId();
    	
    	writeContent();
    	
    	_out.flush();
    }
    
    private void writeId() throws IOException
    {
    	writeShort(_id);
    }
    
    protected abstract void writeContent() throws IOException;

    public abstract void runContent();

    public void setInputStream(ObjectInputStream in) {
        _in = in;
    }

    public void setOutputStream(ObjectOutputStream out) {
        _out = out;
    }

    protected final void writeByte(byte data) throws IOException {
        _out.writeByte(data);
    }

    protected final void writeString(String str) throws IOException {
        _out.writeUTF(str);
    }

    protected final String readString() throws IOException {
        return _in.readUTF();
    }

    protected final byte readByte() throws IOException {
        return _in.readByte();
    }
    
    protected final short readShort() throws IOException
    {
    	return _in.readShort();
    }
    
    protected final void writeShort(short data) throws IOException
    {
    	_out.writeShort(data);
    }

    public void execute() throws IOException {

        try {
            readContent();

            runContent();
        } catch (IOException e) {
            throw new IOException("Packet read failed:" + e);
        }

    }

    public short getId() {
        return _id;
    }
}
